package com.limm.servlet.upload;

import com.limm.dao.upload.UploadDao;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * 处理用户上传的歌曲
 */

@WebServlet(name = "UploadServlet")
public class UploadServlet extends HttpServlet {
    private final String MESSAGE = "上传成功";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        UploadDao uploadDao = new UploadDao();

        //1、创建一个DiskFileItemFactory工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //2、创建一个文件上传解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解决上传文件名的中文乱码
        upload.setHeaderEncoding("UTF-8");
//        factory.setSizeThreshold(1024 * 500);//设置内存的临界值为500K
//        File linshi = new File("E:\\linshi");//当超过500K的时候，存到一个临时文件夹中
//        factory.setRepository(linshi);
        upload.setSizeMax(1024 * 1024 * 50);//设置上传的文件总的大小不能超过50M
        try {
            // 1. 得到 FileItem 的集合 items
            List<FileItem> items = upload.parseRequest(request);

            // 2. 遍历 items:
            for (FileItem item : items) {
                // 若是一个一般的表单域, 打印信息

                String fileName = item.getName();
                long sizeInBytes = item.getSize();
                System.out.println("=======================================");
                System.out.println(fileName);
                System.out.println(sizeInBytes);
                InputStream in = item.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;

                String fileSc = "WEB-INF/resource/music/" + fileName;//文件最终上传的位置
                System.out.println("=======================");
                System.out.println("全路径：" + fileName);
                OutputStream out = new FileOutputStream(fileSc);

                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }


                //插入表


                //上传成功
                response.getWriter().print(MESSAGE);
                out.close();
                in.close();
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

}
